import React, { memo } from 'react';
import { Breadcrumb } from 'antd';
import classnames from 'classnames';
import { NavLink } from 'react-router-dom';

import RcIcon from '../RcIcon';
import './index.less';

export type RcBreadcrumbProps = {
  className?: string;
  onBack?: () => void;
  items?: {
    name: string;
    path?: string;
  }[];
};

const RcBreadcrumb: React.FC<RcBreadcrumbProps> = props => {
  const { className, onBack, items } = props;
  const lastIdx = items ? items.length - 1 : 0;

  return (
    <div className={classnames('rc-breadcrumb_layout', className)}>
      {onBack ? (
        <div className="rc-breadcrumb_back">
          <RcIcon type="back" onClick={onBack} />
          <div className="divider-ver" />
        </div>
      ) : null}
      <Breadcrumb className="rc-breadcrumb" separator=">">
        {items?.map(({ name, path }, idx) => (
          <Breadcrumb.Item key={path || idx}>
            {idx === lastIdx ? name : getItem(name, path)}
          </Breadcrumb.Item>
        ))}
      </Breadcrumb>
    </div>
  );
};

function getItem(name: string, path?: string) {
  return path ? <NavLink to={path}>{name}</NavLink> : name;
}

export default memo(RcBreadcrumb, (p, n) => p.className === n.className && p.items === n.items);
